package com.is2.patchinglife.listener;

import com.is2.patchinglife.manager.LocalDataManager;
import com.is2.patchinglife.manager.NotificationHandler;
import com.is2.patchinglife.util.SensorValues;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

public class LightListener implements SensorEventListener{
		
		// CONSTANTS
		private	final long NORM = 1000000000; // 1s [ns]
		
		// FREQUENCY PARAMETERS
        private double lastAcquire;			// time of last acquired value
        private double minDelay = 0.5; 		// delay [s]
        
        // TROPHY PARAMETERS
        private final long TIMEOUT = 60; 	// timeout [s]
		private final int OFF = 15;			// value offset
        
        // light_01
		private double startLight = -1;			// trophy start time
		private String lightKey = "light_01";
		
		// dark_01
		private double startDark = -1;			// trophy start time
		private String darkKey = "dark_01";
		
		@Override
		/** Activated when sensor accuracy changes **/
		public void onAccuracyChanged(Sensor arg0, int arg1){}

		@Override
		/** Activated when sensor value changes **/
		public void onSensorChanged(SensorEvent event){
			
			// update sensor value in SHARED_MEMORY
			SensorValues.setValue("light",event.values[0]);
			
			// slow down execution frequency
			if((lastAcquire+minDelay)<(event.timestamp/NORM)){
				lastAcquire = event.timestamp/NORM;
				
				// trophy codes
				checkDark01(event.values[0]);
				checkLight01(event.values[0],event.sensor.getMaximumRange());
			}
		}	
		
		// TROPHY: dark_01
		public void checkDark01(float _light){
			if(!LocalDataManager.getGotIT(darkKey) && 
				LocalDataManager.getInhibited("accelerometer") && LocalDataManager.getInhibited("proximity")){	// needed by sensor inhibition
				
				if(_light<OFF && startDark==-1)
					startDark=lastAcquire;
			
				if(SensorValues.getValue("accZ")>-5 && SensorValues.getValue("prox")>0)
					startDark=-1;
				
				if(startDark>0 && (lastAcquire-startDark)>=TIMEOUT){
					LocalDataManager.gotNewTrophy(darkKey);
					NotificationHandler.displayNotificationMessage(LocalDataManager.getName(darkKey),LocalDataManager.getDesc(darkKey),LocalDataManager.getID(darkKey));
				}else if(_light>=OFF)
					startDark=-1;
			}
		}
		
		// TROPHY: light_01
		public void checkLight01(float _light, float _max){
			if(!LocalDataManager.getGotIT(lightKey)){		// needed by sensor inhibition
				
				if(_light>_max-OFF && startLight==-1)
					startLight=lastAcquire;
				
				if(startLight>0 && (lastAcquire-startLight)>=TIMEOUT){
					LocalDataManager.gotNewTrophy(lightKey);
					NotificationHandler.displayNotificationMessage(LocalDataManager.getName(lightKey),LocalDataManager.getDesc(lightKey),LocalDataManager.getID(lightKey));
				}else if(_light<=_max-OFF)
					startLight=-1;
			}
		}
}
